﻿using System;
using System.Collections.Generic;

namespace TopHero
{
    public class HeroBattleState : Singleton<HeroBattleState>, State<Hero>
    {
        public void Enter(Hero t)
        {
            Debug.LogFormat("在地块{0}战斗开始", t.world.PositionToIndex(t.position));

            t.SetTargetPosition(t.position);
            t.SetPropertyValue(PropertyId.SPEED, 0);
        }

        public void Execute(Hero t)
        {
            if (t.GetPropertyValue(PropertyId.SPEED) >= t.GetPropertyValue(PropertyId.MAX_SPEED))
            {
                t.SetPropertyValue(PropertyId.SPEED, 0);
                Cell cell = t.world.GetCell(t.position);
                List<Monster> monsters = cell.GetMonsters();
                if (monsters.Count == 0)
                {
                    t.stateMachine.ChangeState(HeroIdleState.Instance);
                    return;
                }

                Monster m = monsters[Random.Instance.Next(0, monsters.Count - 1)];
                MessageDispatcher.Instance.DispatchMsg(0, t.ID(), m.ID(), MessageType.Attack,
                    t.GetPropertyValue(PropertyId.ATK));


                if (Helper.IsMonstersDead(monsters))
                {
                    t.stateMachine.ChangeState(HeroIdleState.Instance);
                    return;
                }
            }
        }

        public void Exit(Hero t)
        {
            Debug.LogFormat("在地块{0}战斗结束", t.world.PositionToIndex(t.position));

            t.SetPropertyValue(PropertyId.SPEED, 0);
        }

        public bool OnMessage(Hero t, Telegram msg)
        {
            if (msg.msg == MessageType.Attack)
            {
                float damage = (float) msg.extraInfo;
                float hp = t.GetPropertyValue(PropertyId.HP);
                hp = Math.Max(0, hp - damage);
                t.SetPropertyValue(PropertyId.HP, hp);
                return true;
            }

            return false;
        }
    }
}